from pydocx import PyDocX
from docx import Document       # pip install python-docx

# document = Document()

input_doc = 'input.docx'
document = Document(input_doc)

# --- 插入图片到指定位置
context_dc = {
    'signature_picture': 123
}

pic = "temp/a1.jpg"
# run = paragraph.add_run()
# run.add_picture(pic, width = 1400000, height = 1400000)
from docx.shared import Inches

# document.add_picture(pic, width=Inches(1.0), height=Inches(1.0))

table_ls = document.tables
table_i = table_ls[0]

# --- 找出table_i中特定的标签, 如 {{ name }}, 然后将其替换为content_dc中的对应内容
context_dc = {
    'signature_picture': 'temp/a1.jpg',       # 手写电子签名
    'name': '博得',
    'sex': '男',
    'education_degree': '小学生',
    'school': '蓝翔'
}

import re, os


def find_match_by_sign_in_text(text):
    """
    找到text中的标识符sign, 如{{ name }}这类标签

    :param text: 待匹配文本
    :return: 正则匹配结果
    """
    reg = re.compile(r'{{ ?(\w+) ?}}')
    match = reg.search(text)
    return match


def find_context_by_match(match):
    """
    找到match对应的上下文context

    :param match: 正则匹配结果
    :return: 是否为图片is_picture, context_dc中的key和value
    """
    key = match.group(1)     # 变量名
    value = context_dc.get(key)

    is_picture = False
    if key.endswith('_picture'):   # 判断是否为图片
        is_picture = True
    return is_picture, key, value


print('~~~~~~~~~~~~~~~~ 开始遍历table_i')
for row in table_i.rows:
    print('row.cells --- ', len(row.cells))
    for cell in row.cells:
        for p in cell.paragraphs:
            print(p, p.text)
            text = p.text

            if text:
                reg = re.compile(r'{{ ?(\w+) ?}}')
                # match = reg.findall(text)

                match = find_match_by_sign_in_text(text)
                if match:
                    # debug
                    break
                is_picture, key, value = find_context_by_match(match)

                if is_picture:
                    # 插入图片
                    assert value and os.path.isfile(value), '图片value错误!'
                    pic_format_ls = ['.jpg', '.jpeg', '.png']
                    assert os.path.splitext(value)[-1] in pic_format_ls, f'图片格式错误! 必须为{pic_format_ls}!'

                    run = p.add_run()
                    picture = run.add_picture(value)
                else:
                    # 替换变量
                    new_text = reg.sub(value, text, 1)
                    p.text = new_text


row_count = len(table_i.rows)
col_count = len(table_i.columns)


# --- 输出
if 0:
    paragraph = document.add_paragraph('这是个段落。')
    prior_paragraph = paragraph.insert_paragraph_before('这是前面的段落。')
    document.add_heading('这是个标题')
    document.add_heading('The role of dolphins', level=2)

    table = document.add_table(rows=2, cols=2)
    cell = table.cell(0, 1)
    cell.text = '这是第一行第二列的单元格'

    row = table.rows[1]
    row.cells[0].text = '第二行第一列'
    row.cells[1].text = '第二行第二列'

    for row in table.rows:
        for cell in row.cells:
            print(cell.text)

    row_count = len(table.rows)
    col_count = len(table.columns)
    # row = table.add_row()

output_doc = 'output_doc.docx'
document.save(output_doc)


# --------- 转化为html
html = PyDocX.to_html(output_doc)

output_html = 'output_doc.html'
f = open(output_html, 'w', encoding="utf-8")
f.write(html)
f.close()

import os
os.system('open ' + output_doc)
# os.open(output_html)

